//var app = require('express').createServer();
var io = require('socket.io').listen(8000);

//app.listen(8000);

var UsersChatting = '';

var Users = new Array();
var Chats = new Array();

function User(id, displayName, username, pictureLink, chatID){
	this.id = id;
	this.displayName = displayName;
	this.username = username;
	this.pictureLink = pictureLink;
	this.chatID = chatID;
}

if (!Array.prototype.indexOf) {  
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {  
        "use strict";  
        if (this == null) {  
            throw new TypeError();  
        }  
        var t = Object(this);  
        var len = t.length >>> 0;  
        if (len === 0) {  
            return -1;  
        }  
        var n = 0;  
        if (arguments.length > 0) {  
            n = Number(arguments[1]);  
            if (n != n) { // shortcut for verifying if it's NaN  
                n = 0;  
            } else if (n != 0 && n != Infinity && n != -Infinity) {  
                n = (n > 0 || -1) * Math.floor(Math.abs(n));  
            }  
        }  
        if (n >= len) {  
            return -1;  
        }  
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);  
        for (; k < len; k++) {  
            if (k in t && t[k] === searchElement) {  
                return k;  
            }  
        }  
        return -1;  
    }  
}

function UsersChattingInfo(chatID) {
	var temp = new Array();
	var noUsers = 0;

	var UsersChatting = new Array();
	
	for(var i = 0; i < Users.length; i++) {
		console.log("userID: " + Users[i].id);
		if(temp.indexOf(Users[i].id) == -1) {
			temp.push(Users[i].id);
			if(Users[i].chatID == chatID) {
				var tempUser = new Array(Users[i].id, Users[i].displayName, Users[i].username, Users[i].pictureLink);
				UsersChatting.push(tempUser);
			}
		}
	}
	
	//users currently in the chat
	return UsersChatting;
}

//NEW SOCKET CONNECTION
io.sockets.on('connection', function (socket) {

	console.log('Connecting New User');
	
	socket.on('adduser', function(uid, displayName, username, pictureLink, chatID){
		
		// create new client
		socket.client = new User(uid, displayName, username, pictureLink, chatID);
		
		// store the room name in the socket session for this client
		socket.room = chatID;
		
		// send client to correct chat room 
		socket.join(chatID);
		
		// add client to list of users
		Users.push(socket.client);
		
		// add chat to list of chat if it does not already exist
			if(Chats.indexOf(chatID) == -1) {
				Chats.push(socket.client);
			}
		
		//console.log(socket.client.displayName);
		
		UsersChatting = UsersChattingInfo(socket.room);
		io.sockets.in(socket.room).emit('UsersChatting', UsersChatting);
		
		//io.close();

	});	
	
	// when the client emits 'sendchat', this listens and executes
	socket.on('sendchat', function (message) {
		socket.broadcast.to(socket.room).emit('updatechat', socket.client.id, socket.client.displayName, socket.client.username, socket.client.pictureLink, message);
	});
	
	socket.on('disconnect', function () {
		console.log('Disconneting ' + socket.client.displayName);
		//delete displayNames[socket.displayName];
		
		var removedUser = false;
		var i = 0;
		
		do {
			if(Users[i] == socket.client) {
				Users.splice(i, 1);
				console.log("user spliced");
				
			}
			i++;
		} while (i < User.length);
		
		socket.leave(socket.room);
		
		UsersChatting = UsersChattingInfo(socket.room);
		io.sockets.in(socket.room).emit('UsersChatting', UsersChatting);
	});
	
	socket.on('close', function(had_error){
		console.log('server closed');
	});	
	
});